import GjsEditor from '@grapesjs/react'; // 移除了 Canvas，因为 GjsEditor 内部会处理
import grapesjs from 'grapesjs';
import gjsblockbasic from 'grapesjs-blocks-basic';
import gjsPresetWebpage from 'grapesjs-preset-webpage';
import 'grapesjs/dist/css/grapes.min.css';
import React, { useRef, useState } from 'react';
import { useReactToPrint } from 'react-to-print';

const Print = () => {
  const editorContainerRef = useRef(null);
  const editorRef = useRef(null);
  // 修改 Ref 名称以匹配 iframe
  const printIframeRef = useRef(null);
  // State 用于保存打印内容的 srcDoc
  const [printableContent, setPrintableContent] = useState(
    `
          <!DOCTYPE html>
          <html>
            <head>
              <meta charset="utf-8">
              <title>打印内容</title>
              <style type="text/css">
                /* 添加一些基本的打印样式 */
                body { margin: 10mm; /* 示例边距 */ }
              </style>
            </head>
            <body>
            <div>11111</div>
            </body>
          </html>
        `
  );

  // 配置 react-to-print
  const handlePrint = useReactToPrint({
    // content 函数返回 iframe 元素
    contentRef: printIframeRef,
    // 在获取内容前准备 HTML 和 CSS
    onBeforePrint: async () => {
      const editor = editorRef.current;
      if (editor) {
        const html = editor.getHtml() || '';
        const css = editor.getCss({ avoidProtected: true }) || '';
        const contentToPrint = `
              <style type="text/css">
                ${css}
                /* 添加一些基本的打印样式 */
              </style>
              ${html}
        `;
        // 更新 state
        printIframeRef.current.innerHTML = contentToPrint
        setPrintableContent(contentToPrint);
        // 返回 Promise，等待 state 更新和 iframe 渲染
        return new Promise((resolve) => {
          // 给予足够的时间让 iframe 的 srcDoc 更新
          setTimeout(resolve, 150); // 可以根据需要调整延迟
        });
      }
      return Promise.reject('Editor not available');
    },
    // 打印后清理
    onAfterPrint: () => {
      setPrintableContent(''); // 清空内容
      console.log('打印完成或取消。');
    },
  });

  const onEditor = (editor) => {
    console.log('Editor loaded', editor);
    editorRef.current = editor;
  };

  return (
    <div>
      {/* 打印按钮 - onClick 简化 */}
      <button onClick={() => {
        const editor = editorRef.current;
        if (editor) {
          // 直接调用 handlePrint，内容准备在 onBeforeGetContent 中完成
          handlePrint();
        } else {
          alert('编辑器尚未加载完成！');
        }
      }}>打印画布内容</button>

      {/* GrapesJS 编辑器容器 */}
      <div ref={editorContainerRef}>
        <GjsEditor
          grapesjs={grapesjs}
          options={{
            height: '100vh',
            storageManager: false,
          }}
          plugins={[
            gjsPresetWebpage,
            gjsblockbasic
          ]}
          onEditor={onEditor}
        >
          {/* Canvas 会由 GjsEditor 自动渲染，无需显式添加 */}
        </GjsEditor>
      </div>

      {/* 隐藏的 iframe，用于 react-to-print */}
      <div
        // 确保 ref 名称匹配
        ref={printIframeRef}
        style={{
          position: 'fixed',
          left: '-9999px',
          top: '-9999px',
          width: '100%',
          height: '100%',
        }}
        title="Print Content"
      ></div>
    </div>
  );
};

export default Print;
